//------------------------------------------------------------------------------
// <copyright file="AutoCompleteEntryConverter.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using DotBeer.Business.Entities;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using DAnton.Utilities.Extensions;

namespace DotBeer.UI.WPFClient
{
    public class AutoCompleteEntryConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.GetType().IsGenericIEnumerable())
            {
                List<AutoCompleteEntry> items = new List<AutoCompleteEntry>();
                Type[] genericArguments = value.GetType().GetGenericArguments();
                Type itemType = genericArguments[0];

                if (itemType.GetProperties().SingleOrDefault(p => p.Name == "Name") != null)
                {
                    foreach (object item in value as IEnumerable)
                    {
                        itemType = item.GetType();
                        PropertyInfo[] properties = itemType.GetProperties();
                        string name = String.Empty;
                        string imagePath = String.Empty;

                        foreach (PropertyInfo property in properties)
                        {
                            if (property.Name == "Name")
                                name = (string)property.GetValue(item, null);
                            else if (property.Name == "ImagePath")
                                imagePath = (string)property.GetValue(item, null);
                        }

                        if (name != String.Empty)
                            items.Add(new AutoCompleteEntry(name, imagePath));
                    }
                }

                return items;
            }
            else
                return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
